const Base = require("../base.js");
var axios = require("axios");
module.exports = class extends Base {
  async __before() {
    try {
      this.xcxip = this.ctx.header["x-real-ip"] || "127.0.0.1";
    } catch (e) {
      this.xcxip = "127.0.0.1";
    }
    this.roleId = 98; //角色id
    this.sxname = "wxinfo";
    const dxglobalSetting = this.model("dxglobalSetting");
    const { text } = await dxglobalSetting
      .where({ roleId: this.roleId, sxname: this.sxname })
      .find();
    const { AppID, AppSecret } = JSON.parse(text);

    this.access_token = await this.cache("gzhaccess_tokenmaya10");
    if (this.xcxip != "127.0.0.1") {
      this.gzhAppID = AppID;
      this.gzhAppSecret = AppSecret;
      if (!this.access_token) {
        const res = await this.dxGet(
          "https://api.weixin.qq.com/cgi-bin/token",
          {
            grant_type: "client_credential",
            appid: this.gzhAppID,
            secret: this.gzhAppSecret,
          }
        );
        this.access_token = res.access_token;
        await this.cache("gzhaccess_tokenmaya10", res.access_token, {
          timeout: 1000 * 60 * 60 * 1,
        });
      }
    }
    this.ticket = await this.cache("ticket");
    if (!this.ticket) {
      const { ticket } = await this.dxGet(
        "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" +
          this.access_token +
          "&type=jsapi"
      );
      this.ticket = ticket;
      await this.cache("ticket", ticket, {
        timeout: 1000 * 60 * 60 * 1,
      });
    }

    try {
      this.userinfo = await this.analysisToken(this.ctx.header.token);
    } catch (e) {}
    this.wxcharUser = this.model("wxcharUser");
    this.renwu = this.model("renwu", "maya");
    this.jifen = this.model("jifen", "maya");
    this.jieduanlist = this.model("jieduanlist", "maya");
    this.dianzanlist = this.model("dianzanlist", "maya");
    this.jieji = this.model("jieji", "maya");
    this.zhirenwu = this.model("zhirenwu", "maya");
  }
  async getUserInfoAction() {
    const userInfo = await this.wxcharUser
      .where({ id: this.userinfo.id })
      .field("id,headPortrait,nickname")
      .find();
    this.success(userInfo);
  }

  async gheysddfAction() {
    const obj = this.get();
    const { gzhopenid } = await this.wxcharUser
      .where({ openid: this.userinfo.openid })
      .field("gzhopenid")
      .find();
    if (!obj.token) {
      this.success("请传用户的token");
      return;
    }
    const { data } = await this.dxGet(
      "https://h5.shengu.info/api/biz/ai/maya/queryUserInfo",
      "",
      { token: obj.token }
    );
    const jdsdf = await this.wxcharUser
      .where({ unionid: data.unionid })
      .update({
        gzhopenid: data.wxweb_openid,
        headPortrait: data.avatar_url,
        nickname: data.username,
        gzhtoken:obj.token
      });
    // if (!gzhopenid) {}
      if(data.wxweb_openid){
        this.success("操作成功！");
      }else{
        this.fail('获取公众号openid失败')
      }
    
  }

  // 获取字典内容
  async getzidianAction() {
    const id = this.get("id");
    const data = await this.getzdJsList(id);
    this.success(data);
  }

  // 添加随机任务
  async sjkkxcfdAction() {
    const data = await this.getzdJsList("360,361");
    const datab = await this.getzdJsList("362,363");
    const datac = await this.getzdJsList("364");
    const txxrty = await this.getzdJsList("368"); //每日日常任务随机任务的条数
    const txxrtyb = await this.getzdJsList("369"); //每日通关任务随机任务的条数
    const txxrtyc = await this.getzdJsList("370"); //每日副本任务随机任务的条数
    await this.jxcxzfrtrty(data, txxrty, 1);
    await this.jxcxzfrtrty(datab, txxrtyb, 2);
    await this.jxcxzfrtrty(datac, txxrtyc, 3);
 
    this.success("添加成功");
  }
  async addjfensdAction(){
    await this.jifen.add({
      name: "每日登录",
      jifen: 50,
      openid: this.userinfo.openid,
      addTime: this.timeCycle(new Date().getTime()),
    });
    this.success('操作成功')
  }

  async jxcxzfrtrty(data, txxrty, ty) {
    const yixsddf = parseInt(txxrty[0]);
    let jxcxree = [];
    let jxcxreebt = [];
    const dxcxf = await this.renwu
      .where({ openid: this.userinfo.openid, iswanc: 1 })
      .field("title")
      .select();
    const excludeNames = [];
    dxcxf.map((a) => {
      excludeNames.push(a.title);
    });
    data.map((a, ab) => {
      a.map((b) => {
        let renwulx = 1;
        if (ty == 2) {
          renwulx = 2;
        }
        if (ty == 3) {
          renwulx = 3;
        }
        let jxcxrt = new Date();
        let jxcrt = jxcxrt.getTime();
        if (b.extra.indexOf("d") >= 0) {
          let tsxr = b.extra.split(",")[0];
          const jxcdfth = this.timeCycle(
            jxcrt + 1000 * 60 * 60 * 24 * tsxr
          ).split(" ");
          let jxcrxrtyt = excludeNames.filter((item) => item == b.label)[0];
          if (jxcrxrtyt != b.label) {
            jxcxreebt.push({
              title: b.label,
              jifen: ty == 1 ? 50 : 100,
              renwulx,
              extra: b.extra,
              riqi: jxcdfth[0],
              time: jxcdfth[1],
              openid: this.userinfo.openid,
              addTime: this.timeCycle(new Date().getTime()),
            });
          }
        } else {
          const jxcdfth = this.timeCycle(
            jxcrt + 1000 * 60 * 60 * 24 * b.extra
          ).split(" ");
          jxcxree.push({
            title: b.label,
            jifen: ty == 1 ? 50 : 100,
            renwulx,
            extra: b.extra,
            riqi: jxcdfth[0],
            time: jxcdfth[1],
            openid: this.userinfo.openid,
            addTime: this.timeCycle(new Date().getTime()),
          });
        }
      });
    });
    let tzdfrt = yixsddf - jxcxreebt.length;
    if (tzdfrt <= 0) {
      tzdfrt = 1;
    }
    const jxcxrt = this.getRandomItems(jxcxree, tzdfrt, excludeNames);
    let jxcxrytyu = [...jxcxrt, ...jxcxreebt];
    const number = await this.renwu.max("paixu");
    jxcxrytyu.map((a, b) => {
      a.paixu = number + (b + 1);
    });

    try {
      await this.renwu.addMany(jxcxrytyu);
    } catch (e) {}
  }

  // 获取积分
  async getjifenListAction() {
    let zjf = 0;
    const data = await this.jifen
      .where({ openid: this.userinfo.openid })
      .order("id DESC")
      .select();
    data.map((a) => {
      zjf += a.jifen;
    });
    const jxcxzrte = this.timeCyclenyrh();
    const kkxcrt = await this.jifen
      .field("jifen")
      .where({ addTime: jxcxzrte, openid: this.userinfo.openid })
      .select();
    let jrjfre = 0;
    kkxcrt.map((a) => {
      jrjfre += a.jifen;
    });
    this.success({
      zjf,
      jrjfre,
      list: data,
    });
  }

  // 获取积分
  async getjifenListdansxerAction() {
    const zjf = await this.jifen
      .where({ openid: this.userinfo.openid })
      .sum("jifen");

    const jxcxzrte = this.timeCyclenyrh();
    const kkxcrt = await this.jifen
      .where({ addTime: jxcxzrte, openid: this.userinfo.openid })
      .sum("jifen");
    this.success({
      zjf,
      kkxcrt,
    });
  }

  async cxzcfdfdfAction() {
    const data = await this.renwu
      .where({ "renwu.iswanc": 1 })
      .join({
        table: "dxgjadmin.wxcharUser",
        join: "left", //join 方式，有 left, right, inner 3 种方式
        as: "b",
        on: ["renwu.openid", "b.openid"],
      })
      .field(
        "renwu.id,renwu.title,renwu.riqi,renwu.time,renwu.openid,renwu.jifen,b.gzhopenid"
      )
      .select();
    this.success(data);
  }

  // 检测任务是否完成
  async jcrwsfwcAction() {
    const data = await this.renwu
      .where({ "renwu.iswanc": 1 })
      .join({
        table: "dxgjadmin.wxcharUser",
        join: "left", //join 方式，有 left, right, inner 3 种方式
        as: "b",
        on: ["renwu.openid", "b.openid"],
      })
      .field(
        "renwu.id,renwu.title,renwu.riqi,renwu.time,renwu.openid,renwu.jifen,b.gzhopenid"
      )
      .select();
    let kjkxcxer = [];
    let jcxcrtt = [];

    data.map((a) => {
      let ixdsr = a.riqi + " " + a.time;
      const tixtime = new Date(ixdsr).getTime();
      const dqtimexre = new Date().getTime();
      if (dqtimexre >= tixtime) {
        kjkxcxer.push(a.id);
        jcxcrtt.push({
          name: "超时" + a.title,
          riqi: a.riqi,
          time: a.time,
          didian: a.didian,
          beizhu: a.beizhu,
          jifen: a.jifen,
          openid: a.openid,
          gzhopenid: a.gzhopenid,
          addTime: this.timeCycle(new Date().getTime()),
        });
      }
    });
    if (kjkxcxer.length > 0) {
      await this.renwu
        .where({ id: kjkxcxer })
        .update({ iswanc: 3, wcsj: this.timeCycle(new Date().getTime()) });
      // await this.jifen.addMany(jcxcrtt);
      // for (let i = 0; i < jcxcrtt.length; i++) {
      //   console.log({
      //     gzhopenid:jcxcrtt[i].gzhopenid,
      //     title: jcxcrtt[i].name,
      //     wcsj:this.timeCycle(new Date().getTime()),
      //     jifen:jcxcrtt[i].jifen
      //   });
      //   this.fambxsd(jcxcrtt[i].gzhopenid, {
      //     title: jcxcrtt[i].name,
      //     wcsj:this.timeCycle(new Date().getTime()),
      //     jifen:jcxcrtt[i].jifen
      //   });
      // }
    }
    this.success(kjkxcxer);
  }

  // 完成任务
  async wancserAction() {
    const obj = this.post();
    await this.jifen.add({
      name: "完成" + obj.title,
      title: "完成" + obj.title,
      jifen: obj.jifen,
      openid: this.userinfo.openid,
      addTime: this.timeCycle(new Date().getTime()),
    });
    let wcsj = this.timeCycle(new Date().getTime());
    obj.wcsj = wcsj;
    await this.renwu.where({ id: obj.id }).update({ wcsj });
    const { gzhopenid } = await this.wxcharUser
      .where({ openid: this.userinfo.openid })
      .field("gzhopenid")
      .find();
    this.fambxsd(gzhopenid, obj);
    this.success("操作成功！");
  }
  // 阶段完成
  async jieduanwancserAction() {
    const obj = this.post();
    await this.jifen.add({
      name: "完成" + obj.zrwtext,
      title: "完成" + obj.zrwtext,
      jifen: obj.jifen,
      openid: this.userinfo.openid,
      addTime: this.timeCycle(new Date().getTime()),
    });
    let wcsj = this.timeCycle(new Date().getTime());
    obj.wcsj = wcsj;
    const { gzhopenid } = await this.wxcharUser
      .where({ openid: this.userinfo.openid })
      .field("gzhopenid")
      .find();
    obj.title = obj.zrwtext;
    this.fambxsd(gzhopenid, obj);
    this.success("操作成功！");
  }

  // 完成任务
  async sairernwuAction() {
    const obj = this.post();
    await this.jifen.add({
      name: obj.title,
      title: obj.title,
      jifen: obj.jifen,
      openid: this.userinfo.openid,
      addTime: this.timeCycle(new Date().getTime()),
    });
    const { gzhopenid } = await this.wxcharUser
      .where({ openid: this.userinfo.openid })
      .field("gzhopenid")
      .find();
    this.fambxsd(gzhopenid, obj);
    this.success("操作成功！");
  }

  getRandomItems(data, count, excludeNames) {
    // 过滤掉名称在excludeNames中的项
    const filteredData = data.filter(
      (item) => !excludeNames.includes(item.title)
    );

    // 检查是否有足够的项来满足要求
    try {
      if (filteredData.length < count) {
        throw new Error("Not enough items to select from after filtering.");
      }
    } catch (e) {}

    // 随机打乱数据
    const shuffled = filteredData.sort(() => 0.5 - Math.random());

    // 返回前count个项
    return shuffled.slice(0, count);
  }

  // 计算倒计时
  async chatGptAction() {
    const obj = this.get();
    const { data } = await this.ajaxsert(obj.text);
    const jnxcxr = this.extractIntegers(data);
    let msgtext = "";
    jnxcxr.map((a) => {
      if (a > 50) {
        msgtext = a;
      }
    });
    this.success({
      msgtext,
      data,
    });
  }
  async fambxsd(gzhopenid, obj) {
    const res = await this.dxPost(
      "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" +
        this.access_token,
      {
        touser: gzhopenid,
        template_id: "yuKII2qmaJGLezsf6sBPIg450w8d26KXWlWMNBNld4A",
        data: {
          keyword1: {
            value: "完成" + obj.title,
            color: "#173177",
          },
          keyword2: {
            value: obj.wcsj,
            color: "#173177",
          },
          keyword3: {
            value: "奖励积分：" + obj.jifen,
            color: "#173177",
          },
        },
      }
    );
    console.log(res);
  }
  // 生成推广二维码
  async getcreateQrAction() {
    const res = await this.dxPost(
      "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" +
        this.access_token,
      {
        expire_seconds: "2592000",
        action_name: "QR_STR_SCENE",
        action_info: {
          scene: {
            scene_str: this.userinfo.openid,
          },
        },
      }
    );
    this.success({
      ...res,
      qrUrl: "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + res.ticket,
    });
  }
  async thzxcfAction() {
    const sres = await this.dxGet("https://api.weixin.qq.com/sns/userinfo", {
      access_token: this.access_token,
      openid: "oQ9io65SimDysy38qLri4NOgsrlU",
      lang: "zh_CN",
    });
    this.success(sres);
  }

  extractIntegers(text) {
    // 正则表达式匹配整数
    const integerRegex = /-?\b\d+\b/g;
    // 使用正则表达式执行匹配并返回结果
    return text.match(integerRegex) || [];
  }

  ajaxsert(text) {
    return new Promise((resolve, reject) => {
      axios
        .get("https://dxchat.duxinggj.com/indexer", {
          params: { text },
        })
        .then(function (response) {
          resolve(response.data);
        })
        .catch((res) => {
          resolve(ress);
        });
    });
  }

  async getuserpaimAction() {
    const dsdfdt = await this.wxcharUser
      .where({ Applicationid: 98 })
      .field("id,openid,unionid,nickname,headPortrait")
      .select();
    for (let i = 0; i < dsdfdt.length; i++) {
      dsdfdt[i].jifen = await this.jifen
        .where({ openid: dsdfdt[i].openid })
        .sum("jifen");
      if (dsdfdt[i].jifen <= 0) {
        dsdfdt[i].jifen = 0;
      }
    }
    dsdfdt.sort(function (a, b) {
      return b.jifen - a.jifen;
    });
    this.success(dsdfdt);
  }
  // 集市点赞
  async hjsdrereAction() {
    const obj = this.post();
    obj.openid = this.userinfo.openid;
    const dfddsf = await this.dianzanlist.thenAdd(
      {
        ...obj,
        addTime: this.timeCycle(new Date().getTime()),
      },
      obj
    );
    if (dfddsf.type == "exist") {
      await this.dianzanlist.where({ id: dfddsf.id }).delete();
    }
    this.success("操作成功！");
  }

  async jzxcdfdsfAction() {
    const obj = this.post();
    const dijsd = JSON.parse(obj.ds);
    dijsd.map((a) => {
      (a.openid = this.userinfo.openid),
        (a.addTime = this.timeCycle(new Date().getTime()));
    });
    const mxcsdf = await this.jieduanlist.addMany(dijsd);
    this.success(dijsd);
  }
  async ghetysdAction() {
    const kjxzcdfd = await this.jieduanlist
      .where({ openid: this.userinfo.openid })
      .order("id DESC")
      .select();
    const jkxcsdf = await this.zhirenwu
      .where({ openid: this.userinfo.openid })
      .field("zirenwu,wcsj")
      .select();
    for (let i = 0; i < kjxzcdfd.length; i++) {
      const kxcsdff = await this.jieji
        .where({ fid: kjxzcdfd[i].value })
        .order("paixu ASC")
        .select();
      let kdxfcsdf = kxcsdff[0];
      let jxcdsfds = "";
      const jxcxzrte = this.timeCyclenyrh();
      kjxzcdfd[i].wcshukl = await this.zhirenwu
        .where({ openid: this.userinfo.openid, tdid: kjxzcdfd[i].value })
        .field("zirenwu,wcsj")
        .count("id");
      kjxzcdfd[i].zongts = kxcsdff.length;
      jkxcsdf.map((a) => {
        kxcsdff.map((b, idx) => {
          if (a.zirenwu == b.id) {
            if (kjxzcdfd[i].wcshukl == kjxzcdfd[i].zongts) {
              kdxfcsdf = kxcsdff[idx];
            } else {
              kdxfcsdf = kxcsdff[idx + 1];
            }

            jxcdsfds = a.wcsj;
          }
        });
      });

      kjxzcdfd[i].zrwtext = kdxfcsdf.name;
      kjxzcdfd[i].jifen = kdxfcsdf.jifen;

      kjxzcdfd[i].zirenwu = kdxfcsdf.id;
      kjxzcdfd[i].rwwcsj = jxcdsfds;
      kjxzcdfd[i].dqjd = false;
      if (kjxzcdfd[i].rwwcsj == jxcxzrte) {
        kjxzcdfd[i].dqjd = true;
      }

      if (kjxzcdfd[i].wcshukl == kjxzcdfd[i].zongts) {
        kjxzcdfd[i].renwuwc = true;
      }
    }
    this.success(kjxzcdfd);
  }

  async hjjsjddAction() {
    const obj = this.post();
    const { value } = await this.jieduanlist
      .where({ id: obj.id })
      .field("value")
      .find();
    const kjxzcdfd = await this.jieduanlist.where({ id: obj.id }).delete();
    await this.zhirenwu
      .where({ tdid: value, openid: this.userinfo.openid })
      .delete();

    this.success("删除成功");
  }

  async wandajsdAction() {
    const obj = this.post();
    const jxcxzrte = this.timeCyclenyrh();
    const jcsdf = await this.zhirenwu.add({
      tdid: obj.tdid,
      zirenwu: obj.zirenwu,
      openid: this.userinfo.openid,
      wcsj: jxcxzrte,
    });

    const shuliangnum = await this.zhirenwu
      .where({ openid: this.userinfo.openid, tdid: obj.tdid })
      .field("zirenwu,wcsj")
      .count("id");
    const listnum = await this.jieji
      .where({ fid: obj.tdid })
      .order("paixu ASC")
      .count("id");
    if (shuliangnum == listnum) {
      //完成任务
      await this.jieduanlist.where({ id: obj.id }).update({ iswc: 2 });
    }
    this.success("操作成功");
  }

  async xzxcjieduanlistAction() {
    const ksdfd = await this.jieduanlist
      .where({ openid: this.userinfo.openid })
      .field("value")
      .select();
    this.success(ksdfd);
  }

  async hxcdfdfAction() {
    const obj = this.get();
    const { value } = await this.jieduanlist
      .where({ id: obj.id })
      .field("value")
      .find();
    const list = await this.jieji
      .where({ fid: value })
      .order("paixu ASC")
      .select();
    const kxcdsf = await this.zhirenwu
      .where({ openid: this.userinfo.openid, tdid: value })
      .select();
    list.map((a) => {
      kxcdsf.map((b) => {
        if (a.id == b.zirenwu) {
          a.cls = "cls";
          a.wcsj = b.wcsj;
        }
      });
    });
    this.success(list);
  }

  async hjjsddfAction() {
    const jscadsfs = await this.jieduanlist
      .where({ openid: this.userinfo.openid, iswc: 1 })
      .count("id");
    this.success(jscadsfs);
  }
  async iscfjsdAction() {
    const data = await this.getzdJsList("376,375");
    const lister = this.getTwoUniqueItems(data[1], data[0]);
    lister.map((a) => {
      a.openid = this.userinfo.openid;
      a.addTime = this.timeCycle(new Date().getTime());
    });
    const mxcsdf = await this.jieduanlist.addMany(lister);
    this.success("添加成功");
  }

  getTwoUniqueItems(arr, nle) {
    if (arr.length < 2) return arr; // 如果数组长度小于2，则返回原数组

    let uniqueItems = [];
    let randomIndexes = new Set(); // 使用Set存储随机索引，确保不重复

    while (uniqueItems.length < nle) {
      const randomIndex = Math.floor(Math.random() * arr.length);
      if (!randomIndexes.has(randomIndex)) {
        randomIndexes.add(randomIndex);
        uniqueItems.push(arr[randomIndex]);
      }
    }

    return uniqueItems;
  }

  // 通过id集合返回字典列表
  async getzdJsList(xeids) {
    const dxDictionarymanagement = this.model("dxDictionarymanagement");
    const ids = xeids.split(",");
    const datas = [];
    const res = await dxDictionarymanagement
      .where({
        id: ids,
      })
      .select();
    ids.map((b) => {
      let obj = null;
      res.map((a) => {
        if (a.id == b) {
          obj = this.jsonx(a);
        }
      });
      datas.push(obj);
    });
    return datas;
  }

  jsonx(data) {
    if (data.type == 3) {
      data.text = data.text.split(",");
    }
    if (data.type == 5 || data.type == 6 || data.type == 7) {
      try {
        data.text = JSON.parse(data.text);
      } catch (e) {}
    }
    return data.text;
  }
};
